package com.yijdn.common.utils;

import com.alibaba.fastjson.JSON;
import javafx.scene.control.Pagination;
import org.assertj.core.util.Maps;

import java.util.*;

/**
 * json 转换工具类
 * @author zww
 * @date 2018-03-25 09:22
 * <p>
 * Email 971762302@qq.com
 * <p>
 * Describe:
 */
public class JsonUtils {

    public static String objectToString(Object obj){
        return JSON.toJSONString(obj);
    }

    public static<T> T jsonToObject(String json, Class<T> clazz){
        T obj = null;
        try {
            obj =JSON.parseObject(json,clazz);
        } catch (Exception e){}
        return  obj;
    }

    public static<T> List<T> mapToObjects(String json, Class<T> clazz){
        List<T> list = Collections.emptyList();
        try {
            list = JSON.parseArray(json, clazz);
        } catch (Throwable e){}
        return list;
    }


    public static void main(String[] args) {
        Person person = new Person();
        person.setId(1L);
        person.setName("小明");
        person.setSex(1);
        String json = objectToString(person);
        System.out.println("person:"+json);
        System.out.println("--------------");
        Person person1 = jsonToObject(json, Person.class);
        System.out.println(person1);
        System.out.println("-----------");
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String, Object> map1= new HashMap<>();
        map1.put("id",2L);
        map1.put("name","小红");
        map1.put("sex",0);
        list.add(map1);

        String listMap = objectToString(list);

        List<Person> personList = mapToObjects(listMap, Person.class);
        System.out.println("personlist size: "+ personList.size());
        for(Person entity : personList){
            System.out.println(entity);
        }

    }
}


class Person {
    private Long id;

    private String name;

    private Integer sex;

    private String address;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex=" + sex +
                ", address='" + address + '\'' +
                '}';
    }
}